package whf.framework.tools.generator.db;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.util.List;

import whf.framework.log.Log;
import whf.framework.log.LogFactory;
import whf.framework.tools.generator.ClassGenerator;
import whf.framework.tools.generator.GeneratorException;
import whf.framework.tools.generator.cfg.Config;
import whf.framework.tools.generator.cfg.ConfigFactory;

/**
 * @author wanghaifeng
 *
 */
public class DBCodeGenerator {
	private static Log log = LogFactory.getLog(DBCodeGenerator.class);
	private Config config;
	private AbstractTableGetter tableGetter;

	public DBCodeGenerator(Config config) throws Exception{
		this.config = config;
		Class cls = Class.forName(this.config.getTableParser());
		Constructor con = cls.getConstructor(new Class[]{Config.class});
		this.tableGetter = (AbstractTableGetter)con.newInstance(new Object[]{this.config});
	}

	public void generate() throws GeneratorException, IOException, Exception {
		List list = this.tableGetter.getTables();
		try{
			for(int i=0;i<list.size();i++){
				Table table = (Table)list.get(i);
				log.debug(table);
				ClassGenerator gen = new ClassGenerator(this.config, table);
				gen.generate();
	        }
		}finally{
			ClassGenerator.doFinalize();
		}
	}

	public static void main(String[] args) throws Exception{
		DBCodeGenerator dbcg = new DBCodeGenerator(ConfigFactory.getConfigInstance("gjj"));
		dbcg.generate();
	}
}
